import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import './index.less';
import { Button, Checkbox, DatePicker, Input, InputNumber, message, Radio, Select, Space, TimePicker, TreeSelect, Upload } from 'antd';
import { cloneDeep, isArray, isEmpty, isNil } from 'lodash';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
import Viewer from 'react-viewer';
import OSS from '@/utils/oss';
import { Icon } from '../index';
import FormSwitch from './FormSwitch';
import InputConcatSelect from './InputConcatSelect';
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;
const { TextArea } = Input;
const { SHOW_PARENT } = TreeSelect;
const { Group } = Radio;
const { RangePicker } = DatePicker;
const FormNode = (props) => {
    const { type = 'input', placeholder, disabled, options, treeData, value, onChange, suffix, min, max, keys, direction = 'horizontal', treeCheckable = false, maxImgs = 10, maxSize = 500, tips, accept, rows = 4, showSearch = false, filterOption = false, onSearch = () => { }, ...other } = props;
    const uploadRef = useRef();
    const [nodeValue, setNodeValue] = useState(value);
    const [imgVisible, setImgVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [treeOptions, setTreeOptions] = useState(treeData);
    useEffect(() => {
        setTreeOptions(treeData);
    }, [treeData]);
    useEffect(() => {
        if (['img', 'annex'].includes(type)) {
            !Array.isArray(value) && setNodeValue([]);
            console.log(value, 'value');
            if (isArray(value)) {
                value.forEach((item) => {
                    item.name = decodeURI(item.name);
                });
            }
            // 头像上传初始化值为数组类型
            !Array.isArray(value) && setNodeValue([]);
        }
    }, [type, value]);
    const valueChange = (event) => {
        let val;
        const flag = [
            'multipleSelect',
            'switch',
            'rangeDate',
            'select',
            'checkbox',
            'tree',
            'number',
            'inputAndSelect',
            'img',
            'annex',
            'datePicker',
            'timePicker',
            'rangePicker'
        ].includes(type);
        if (flag) {
            val = event;
        }
        else {
            val = event.target.value;
        }
        if (type === 'number') {
            if (!isNil(min) && val < min) {
                val = min;
            }
            if (!isNil(max) && val > max) {
                val = max;
            }
        }
        setNodeValue(val);
        onChange && onChange(val);
    };
    // upload 图片处理
    useEffect(() => {
        if (type !== 'img')
            return;
        if (uploadRef.current) {
            // console.log(uploadRef.current.upload.props.onChange)
        }
    }, [uploadRef]);
    const beforeUpload = (file) => {
        // 类型由外部传入  待修改
        return new Promise((resolve, reject) => {
            const isJpgOrPng = file.type === 'image/jpg' ||
                file.type === 'image/png' ||
                file.type === 'image/jpeg';
            const fileIsLtMaxSize = file.size / 1024 / 1024 < maxSize;
            if (type === 'img' && !isJpgOrPng) {
                message.error('只能上传jpg/png格式文件!');
                return reject(file);
            }
            if (!fileIsLtMaxSize) {
                message.error(`文件不能超过${maxSize}MB!`);
                return reject(file);
            }
            return resolve(true);
        });
    };
    const customRequest = async ({ file }) => {
        const imgs = cloneDeep(nodeValue) || [];
        // /capacity-platform/platform 目标文件夹路径 __ 分割符号
        const res = await OSS.put(`/capacity-platform/platform/${file.uid}__${file.name}`, file);
        if (res) {
            const { url, name } = res;
            imgs.push({ thumbUrl: url, name: name.split('__')[1], url });
            setNodeValue(imgs);
            valueChange && valueChange(imgs);
        }
    };
    const uploadButton = (_jsx("div", { children: _jsx("div", { style: { marginTop: 8 }, children: "\u4E0A\u4F20" }) }));
    const fileRemove = (file) => {
        const arrList = cloneDeep(nodeValue) || [];
        const target = arrList.filter((item) => item.thumbUrl !== file.thumbUrl);
        setNodeValue(target);
        onChange && onChange(target);
    };
    const onPreview = (file) => {
        setImgVisible(true);
        setPreviewImage(file.thumbUrl);
    };
    const onAnnexPreview = async (file) => {
        const targetUrl = file.thumbUrl.replace('http://capacity-platform.oss-cn-hangzhou.aliyuncs.com', '');
        try {
            const result = await OSS.get(decodeURI(targetUrl));
            const blob = new Blob([result.content], {
                type: 'application/octet-stream'
            });
            const download = document.createElement('a');
            download.href = window.URL.createObjectURL(blob);
            download.download = file.name;
            download.click();
            window.URL.revokeObjectURL(download.href);
        }
        catch (e) {
            console.log(e);
        }
    };
    switch (type) {
        case 'text':
            return _jsx("div", { children: value });
        case 'datePicker':
            console.log(nodeValue, 'nodeValue');
            return (_jsx(DatePicker, { onChange: valueChange, value: nodeValue ? moment(nodeValue) : null, style: { width: '100%' }, disabled: disabled, ...other }));
        case 'timePicker':
            return (_jsx(TimePicker, { onChange: valueChange, value: nodeValue ? moment(nodeValue) : null, disabled: disabled, ...other }));
        case 'rangePicker':
            return (_jsx(RangePicker, { onChange: valueChange, value: nodeValue, disabled: disabled, ...other }));
        case 'radio':
            return (_jsx(Group, { onChange: valueChange, value: nodeValue, disabled: disabled, ...other, children: _jsx(Space, { direction: direction, children: options &&
                        options.length > 0 &&
                        options.map((item) => (_jsx(Radio, { value: item.value, children: item.label }, item.value))) }) }));
        case 'input':
            return (_jsx(Input, { className: 'customFormNodeInput', onChange: valueChange, value: nodeValue, disabled: disabled, placeholder: placeholder, suffix: suffix, ...other }));
        case 'select':
        case 'multipleSelect':
            const rest = {};
            if (type === 'multipleSelect') {
                rest.mode = 'multiple';
            }
            if (showSearch) {
                rest.onSearch = onSearch;
            }
            return (_jsx(Select, { ...rest, ...other, onChange: valueChange, value: nodeValue, placeholder: placeholder, style: { minWidth: 80, width: other.width }, disabled: disabled, showSearch: showSearch, filterOption: filterOption, children: options &&
                    options.length &&
                    options.map((i) => (_jsx(Option, { value: i.value, children: i.label }, i.value))) }));
        case 'checkbox':
            return (_jsx(CheckboxGroup, { onChange: valueChange, value: nodeValue, options: options, disabled: disabled, ...other }));
        case 'tree':
            return (_jsx(TreeSelect, { onChange: valueChange, value: nodeValue, style: { width: '100%', minWidth: 100 }, allowClear: true, treeData: treeOptions, treeCheckable: treeCheckable, showCheckedStrategy: SHOW_PARENT, placeholder: placeholder, disabled: disabled, ...other }));
        case 'textarea':
            return (_jsx(TextArea, { placeholder: placeholder, onChange: valueChange, value: nodeValue, rows: rows, disabled: disabled, ...other }));
        case 'switch':
            return _jsx(FormSwitch, { onChange: valueChange, value: nodeValue, ...other });
        case 'number':
            return (_jsx(InputNumber, { min: min, onChange: valueChange, value: nodeValue, style: { width: '100%' }, disabled: disabled, max: max, ...other }));
        case 'inputAndSelect':
            return (_jsx(InputConcatSelect, { keys: keys, onChange: valueChange, value: nodeValue, options: options, ...other }));
        case 'img':
            return (_jsxs("div", { children: [_jsx(Viewer, { visible: imgVisible, noFooter: true, onMaskClick: () => {
                            setImgVisible(false);
                        }, onClose: () => {
                            setImgVisible(false);
                        }, images: [{ src: previewImage }] }), _jsx(Upload, { ref: uploadRef, fileList: nodeValue, listType: "picture-card", accept: accept, name: "file", maxCount: maxImgs, beforeUpload: beforeUpload, customRequest: customRequest, onRemove: fileRemove, disabled: disabled, onPreview: onPreview, ...other, children: !disabled && (isEmpty(nodeValue) || nodeValue.length) < maxImgs
                            ? uploadButton
                            : null }), tips ? (_jsxs("div", { className: 'uploadTipsBox', children: [_jsx(Icon, { type: 'jack-jingshi1' }), _jsxs("span", { children: ["\u00A0", tips] })] })) : null] }));
        case 'annex': // 附件
            return (_jsxs("div", { children: [_jsx(Upload, { ref: uploadRef, fileList: nodeValue, accept: accept, name: "file", maxCount: maxImgs, beforeUpload: beforeUpload, customRequest: customRequest, onRemove: fileRemove, disabled: disabled, onPreview: onAnnexPreview, ...other, children: _jsx(Button, { disabled: disabled, icon: _jsx(Icon, { type: 'jack-upload-2-fill' }), children: "\u4E0A\u4F20\u6587\u4EF6" }) }), tips ? (_jsxs("div", { className: 'uploadTipsBox', children: [_jsx(Icon, { type: 'jack-jingshi1' }), _jsxs("span", { children: ["\u00A0", tips] })] })) : null] }));
        default:
            return null;
    }
};
export default FormNode;
